<?php
/*
* StiPHPcms, A web Content management System made with PHP/MySQL
* JordSti : jord52@gmail.com
* Version : 0.0.1
*
* Copyright (C) 2009  jord52@gmail.com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

class Module {
	private $cms;
	private $auth_ext;
	private $rank_to_upload;
	private $thumb_width;
	private $thumb_height;
	
	public $name;
	public $version;
	public $author;

	public function __construct($cms)
	{
		$this->name = "ImageUploader (STI)";
		$this->version = "0.0.1";
		$this->author= "StiTeam";
		
		$this->cms = $cms;
		$this->auth_ext = 'jpg,gif,png';
		
		if(!$this->cms->isSettingExist("imageuploader_rank_to_upload"))
		{
			$this->install();
		}
		
		$this->rank_to_upload = $cms->settings['imageuploader_rank_to_upload'];
		$this->thumb_width = $cms->settings['imageuploader_thumb_width'];
		$this->thumb_height = $cms->settings['imageuploader_thumb_height'];
		
	}
	
	public function run()
	{
		if(isset($_GET['t']))
		{
			$task = $_GET['t'];
		}
		else
		{
			$task = 'default';
		}
		
		if($task=='default')
		{
			$this->defaultPage();
		}
		else if($task=='uploadform')
		{
			$this->uploadForm();
		}
		else if($task=='upload')
		{
			$this->uploadImage();
		}
		else if($task=='view')
		{
			$this->viewImage();
		}
		else if($task=='allimg')
		{
			$this->allImageList();
		}
		else if($task=='myimg')
		{
			$this->myImageList();
		}
		
	}
	
	public function allImageList()
	{
		$dt = $this->cms->sql_query("SELECT * FROM %prefix%user_images ORDER BY timestamp DESC");
		
		$html = '<p>'.$this->lang('imgupload_public_img').'</p><table width="90%"><tr>';
		
		$i = 0;
		
		while($data=mysql_fetch_array($dt))
		{

			$html .= '<td><a href="mod.php?mod=imageuploader&t=view&iid='.$data['id'].'"><img src="'.$data['thumb_url'].'"></a></td>';
				
			$i++;
				
			if($i==4)
			{
				$html .= '</tr><tr>';
				$i = 0;
			}

		}

		$html .= '</tr></table>';
		
		$this->cms->renderHeader($this->lang('imgupload_image_list'));
		$this->cms->renderMenu();
		
		$this->cms->addFrame("",$html);
	}
	
	public function myImageList()
	{
		if($this->cms->isUserLog())
		{
			$user_id = $_SESSION['user_id'];
			$dt = $this->cms->sql_query("SELECT * FROM %prefix%user_images WHERE user_id=$user_id ORDER BY timestamp DESC LIMIT 8");
			
			$html = '<p>'.$this->lang('imgupload_my_images').'</p>
			<table width="90%"><tr>';
			
			$i = 0;
			while($data=mysql_fetch_array($dt))
			{

				$html .= '<td><a href="mod.php?mod=imageuploader&t=view&iid='.$data['id'].'"><img src="'.$data['thumb_url'].'"></a></td>';
				
				$i++;
				
				if($i==4)
				{
					$html .= '</tr><tr>';
					$i = 0;
				}

			}
			
			$html .= '</tr></table>';
			
			$this->cms->renderHeader($this->lang('imgupload_my_images'));
			$this->cms->renderMenu();
			$this->cms->addFrame("",$html);
		}
	}
	
	public function defaultPage()
	{
		$html = '';
		
		if($this->rankToUpload())
		{
			$html .= '<p><a href="mod.php?mod=imageuploader&t=uploadform">'.$this->lang('imgupload_upload_link').'</a></p>';
		}
		
		
		if($this->cms->isUserLog())
		{
			$user_id = $_SESSION['user_id'];
			$dt = $this->cms->sql_query("SELECT * FROM %prefix%user_images WHERE user_id=$user_id ORDER BY timestamp DESC LIMIT 8");
			
			$html .= '<p>'.$this->lang('imgupload_my_images').'</p>
			<table width="90%"><tr>';
			
			$i = 0;
			while($data=mysql_fetch_array($dt))
			{

				$html .= '<td><a href="mod.php?mod=imageuploader&t=view&iid='.$data['id'].'"><img src="'.$data['thumb_url'].'"></a></td>';
				
				$i++;
				
				if($i==4)
				{
					$html .= '</tr><tr>';
					$i = 0;
				}

			}
			
			$html .= '</tr></table><p><a href="mod.php?mod=imageuploader&t=myimg">'.$this->lang('imgupload_see_all').'</a></p>';
		}
		
		
		$dt = $this->cms->sql_query("SELECT * FROM %prefix%user_images ORDER BY timestamp DESC LIMIT 8");
		
		$html .= '<p>'.$this->lang('imgupload_public_img').'</p><table width="90%"><tr>';
		
		$i = 0;
		
		while($data=mysql_fetch_array($dt))
		{

			$html .= '<td><a href="mod.php?mod=imageuploader&t=view&iid='.$data['id'].'"><img src="'.$data['thumb_url'].'"></a></td>';
				
			$i++;
				
			if($i==4)
			{
				$html .= '</tr><tr>';
				$i = 0;
			}

		}

		$html .= '</tr></table><p><a href="mod.php?mod=imageuploader&t=allimg">'.$this->lang('imgupload_see_all').'</a></p>';
		
		$this->cms->renderHeader($this->lang('imgupload_image_list'));
		$this->cms->renderMenu();
		
		$this->cms->addFrame("",$html);
		
	}
	
	public function uploadForm()
	{
		if(!$this->rankToUpload())
		{
			$this->cms->error($this->lang('right_error'));
		}
		
		$this->cms->loadStiCodeScript();
		
		require_once("core/sticode.php");
		
		$html = '
		<form name="upload_img" enctype="multipart/form-data" method="post" action="mod.php?mod=imageuploader&t=upload">
		<fieldset>
		<legend>'.$this->lang('imgupload_upload_image').'</legend>
		<p><label for="img_name">'.$this->lang('imgupload_img_name').' : </label><input type="text" id="img_name" name="img_name" size="24" maxlength="64"></p>
		<p><label for="img_file">'.$this->lang('imgupload_img_file').' : </label><input type="file" id="img_file" name="img_file" size="30"></p>
		'.StiCodeHTMLFormBar('description').'
		<p><label for="description">'.$this->lang('imgupload_description').' </label><br /><textarea cols="40" rows="8" name="description" id="description"></textarea></p>
		<p><input type="submit" value="'.$this->lang('imgupload_upload').'"></p>
		</fieldset>';
		
		$this->cms->renderHeader($this->lang('imgupload_upload_link'));
		$this->cms->renderMenu();
		
		$this->cms->addFrame("",$html);
	}
	
	public function uploadImage()
	{
		if(!$this->rankToUpload())
		{
			$this->cms->error($this->lang('right_error'));
		}
		
		$tmp_name = $_FILES['img_file']['tmp_name'];
		$name = $_FILES['img_file']['name'];
		
		if(!is_uploaded_file($tmp_name))
		{
			exit("File isn't uploaded !");
		}
		
		require_once("core/tools/string.php");
		
		$_POST = array_sql_escape($_POST);
		$_POST = array_htmlentities($_POST);
		
		$img_name = $_POST['img_name'];
		$description = $_POST['description'];
		
		$ext = substr($name,(strlen($name)-3));
		$ext = strtolower($ext);
		
		if($ext=='jpg')
		{
			$img = imagecreatefromjpeg($tmp_name);
		}
		else if($ext=='gif')
		{
			$img = imagecreatefromgif($tmp_name);
		}
		else if($ext=='png')
		{
			$img = imagecreatefrompng($tmp_name);
		}
		else
		{
			exit('Unsupported format : '.$ext);
		}
		
		$x = imagesx($img);
		$y = imagesy($img);
		
		if($x <= $this->thumb_width && $y <= $this->thumb_height)
		{
			$path = 'images/uploads/'.$img_name.'.png';
			
			if(file_exists($path))
			{
				$path = 'images/uploads/'.dechex(time()).$img_name.'.png';
			}
			
			imagepng($path);
			chmod($path,0777);
			
			$path_thumb = $path;
			
		}
		else if($x < $y)
		{
			$new_y = $this->thumb_height;
			$new_x = ($new_y*$x)/$y;
			
			$img_thumb = imagecreatetruecolor($new_x,$new_y);
			imagecopyresized($img_thumb,$img,0,0,0,0,$new_x,$new_y,$x,$y);
			
			$path = 'images/uploads/'.$img_name.'.png';
			$path_thumb = 'images/thumbs/'.$img_name.'.png';
			
			if(file_exists($path))
			{
				$path = 'images/uploads/'.dechex(time()).$img_name.'.png';
				$path_thumb = 'images/thumbs/'.dechex(time()).$img_name.'.png';
			}
			
			imagepng($img,$path);
			imagepng($img_thumb,$path_thumb);
		}
		else if($y < $x)
		{
			$new_x = $this->thumb_width;
			$new_y = ($new_x*$y)/$x;
			
			$img_thumb = imagecreatetruecolor($new_x,$new_y);
			imagecopyresized($img_thumb,$img,0,0,0,0,$new_x,$new_y,$x,$y);
			
			$path = 'images/uploads/'.$img_name.'.png';
			$path_thumb = 'images/thumbs/'.$img_name.'.png';
			
			if(file_exists($path))
			{
				$path = 'images/uploads/'.dechex(time()).$img_name.'.png';
				$path_thumb = 'images/thumbs/'.dechex(time()).$img_name.'.png';
			}
			
			imagepng($img,$path);
			imagepng($img_thumb,$path_thumb);
		}
		else if($x==$y)
		{
			$new_y = $this->thumb_height;
			$new_x = $this->thumb_width;
			
			$img_thumb = imagecreatetruecolor($new_x,$new_y);
			imagecopyresized($img_thumb,$img,0,0,0,0,$new_x,$new_y,$x,$y);
			
			$path = 'images/uploads/'.$img_name.'.png';
			$path_thumb = 'images/thumbs/'.$img_name.'.png';
			
			if(file_exists($path))
			{
				$path = 'images/uploads/'.dechex(time()).$img_name.'.png';
				$path_thumb = 'images/thumbs/'.dechex(time()).$img_name.'.png';
			}
			
			imagepng($img,$path);
			imagepng($img_thumb,$path_thumb);
		}
		
		
		$stamp = time();
		$user_id = $_SESSION['user_id'];
		
		$this->cms->sql_query("INSERT INTO %prefix%user_images VALUES('','$img_name','$path','$path_thumb',$stamp,$user_id,'$description')");

		$this->cms->renderHeader($this->lang('imgupload_my_images'));
		$this->cms->renderMenu();
		
		$this->cms->addFrame("",$this->lang('imgupload_image_uploaded').' <br /> '.$this->lang('imgupload_path').': '.$path.' <br /> '.$this->lang('imgupload_thumb_path').': '.$path_thumb);
		
	}
	
	public function viewImage()
	{
		if(isset($_GET['iid']))
		{
			if(is_numeric($_GET['iid']))
			{
				$img_id = $_GET['iid'];
			}
			else
			{
				$this->cms->error('','index.php');
			}
		}
		else
		{
			$this->cms->error('','index.php');
		}
		
		$dt = $this->cms->sql_query("SELECT i.id,i.img_name,i.url,i.timestamp,i.description,u.username FROM %prefix%user_images i JOIN %prefix%users u ON(u.id=i.user_id) WHERE i.id=$img_id");
		
		if(mysql_num_rows($dt)==0)
		{
			$this->cms->error($this->lang('imgupload_image_not_found'));
		}
		
		$data = mysql_fetch_array($dt);
		
		
		$dis = getimagesize($data['url']);
		$img_w = $dis[0];
		$img_h = $dis[1];
		
		require_once("core/tools/filesize.php");
		require_once("core/sticode.php");
		
		$size = new FileSize($data['url']);
		
		if($img_w > 500)
		{
			$n_img_w = 500;
			$n_img_h = ($n_img_w*$img_h)/$img_w;
		}
		else
		{
			$n_img_w = $img_w;
			$n_img_h = $img_h;
		}
		
		$html = '<h3>'.$data['img_name'].'</h3>
		<p><em>'.$img_w.'x'.$img_h.' - '.$size->getSmallUnitFormattedSize().'</em></p>
		<img src="'.$data['url'].'" width="'.$n_img_w.'" height="'.$n_img_h.'">
		<p>'.parseStiCode($data['description']).'</p>
		<p>URL : <a href="'.$this->cms->getExternalUrl().$data['url'].'">'.$this->cms->getExternalUrl().$data['url'].'</a></p>
		<p>'.$data['username'].' - '.date($this->lang('dateformat'),$data['timestamp']).'</p>
		';
		
		$this->cms->renderHeader('');
		$this->cms->renderMenu();
		$this->cms->addFrame($data['img_name'],$html);
	}
	
	public function rankToUpload()
	{
		if($this->cms->getUserRank()<$this->cms->settings['imageuploader_rank_to_upload'])
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	
	public function lang($key)
	{
		return $this->cms->lang[$key];
	}
	
	public function install()
	{
		$this->cms->sql_query("CREATE TABLE `%prefix%user_images` (
				`id` INT( 25 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
				`img_name` VARCHAR( 64 ) NOT NULL ,
				`url` VARCHAR( 128 ) NOT NULL ,
				`thumb_url` VARCHAR( 128 ) NOT NULL ,
				`timestamp` INT( 25 ) NOT NULL ,
				`user_id` INT( 25 ) NOT NULL ,
				`description` TEXT NOT NULL
				) ENGINE = MYISAM ");
		
		$this->cms->addSetting('imageuploader_rank_to_upload',1);
		$this->cms->addSetting('imageuploader_thumb_width',140);
		$this->cms->addSetting('imageuploader_thumb_height',140);
	}
}

class AdminModule {
	private $cms;
	
	public function __construct($cms)
	{
		$this->cms = $cms;
	}
	
	public function lang($key)
	{
		return $this->cms->lang[$key];
	}
	
	public function run()
	{
		if(isset($_GET['t']))
		{
			$task = $_GET['t'];
		}
		else
		{
			$task = 'default';
		}
		
		if($task=='default')
		{
			$this->imageList();
		}
		else if($task=='delete')
		{
			$this->deleteImage();
			$this->imageList();
		}
		else if($task=='edit')
		{
			$this->imageEditForm();
		}
		
	}
	
	public function imageList()
	{
		$dt = $this->cms->sql_query("SELECT i.id,i.img_name,i.url,i.user_id,u.username,i.timestamp FROM %prefix%user_images i JOIN %prefix%users u ON(u.id=i.user_id) ORDER BY i.id DESC");
		
		$html = '<table width="90%">
		<tr class="rowhead">
		<td>'.$this->lang('imgupload_img_name').'</td>
		<td>'.$this->lang('imgupload_uploaded_by').'</td>
		<td>-</td>
		<td>-</td>
		</tr>
		';
		
		$row = 'row01';
		
		while($data = mysql_fetch_array($dt))
		{
			$html .= '<tr class="'.$row.'">
			<td><a href="'.$data['url'].'" target="_blank">'.$data['img_name'].'</td>
			<td><a href="profile.php?pid='.$data['user_id'].'">'.$data['username'].'</a></td>
			<td>'.date($this->lang('dateformat'),$data['timestamp']).'</td>
			<td><a href="admin.php?mod=imageuploader&t=edit&iid='.$data['id'].'">'.$this->lang('edit').'</a> | <a href="admin.php?mod=imageuploader&t=delete&iid='.$data['id'].'">'.$this->lang('delete').'</a></td>
			</tr>';
			
			if($row=='row01')
			{
				$row = 'row02';
			}
			else
			{
				$row = 'row01';
			}
		}
		
		$html .= '</table>';
		
		$this->cms->renderHeader('Image Uploader Admin');
		$this->cms->renderMenu();
		$this->cms->addFrame($this->lang('imgupload_image_list'),$html);
	}
	
	private function deleteImage()
	{
		if(isset($_GET['iid']))
		{
			if(is_numeric($_GET['iid']))
			{
				$img_id = $_GET['iid'];
			}
			else
			{
				$this->cms->error('','index.php');
			}
		}
		else
		{
			$this->cms->error('','index.php');
		}
		
		$this->cms->sql_query("DELETE FROM %prefix%user_images WHERE id=$img_id");
	}
	
	public function imageEditForm()
	{
		if(isset($_GET['iid']))
		{
			if(is_numeric($_GET['iid']))
			{
				$img_id = $_GET['iid'];
			}
			else
			{
				$this->cms->error('','index.php');
			}
		}
		else
		{
			$this->cms->error('','index.php');
		}
		
		$dt = $this->cms->sql_query("SELECT * FROM %prefix%user_images WHERE id=$img_id");
		
		if(mysql_num_rows($dt)==0)
		{
			$this->cms->error($this->lang('imgupload_image_not_found'));
		}
		
		require_once("core/tools/string.php");
		require_once("core/tools/image_html.php");
		require_once("core/sticode.php");
		$this->cms->loadStiCodeScript();
		$data = mysql_fetch_array($dt);
		$data = array_stripslashes($data);

		$img_info = image_resize_html($data['url']);
		
		$html = '<form name="img_edit" method="post" action="admin.php?mod=imageuploader&t=save&iid='.$data['id'].'">
		<fieldset>
		<legend>'.$this->lang('imgupload_image_editor').'</legend>
		<p><em>'.$img_info[0][0].'x'.$img_info[0][1].'</em></p>
		<p>'.$img_info[2].'</p>
		<p>Url : '.$data['url'].'</p>
		<p><label for="img_name">'.$this->lang('imgupload_img_name').' : </label><input type="text" size="36" maxlength="64" value="'.$data['img_name'].'" name="img_name" id="img_name"></p>
		'.StiCodeHTMLFormBar('description').'
		<p><label for="description">'.$this->lang('imgupload_description').'</label><br /><textarea name="description" id="description" cols="40" rows="8">'.$data['description'].'</textarea></p>
		<p>'.date($this->lang('dateformat'),$data['timestamp']).'</p>
		<p><input type="submit" value="'.$this->lang('save').'"></p>
		</fieldset>
		</form>
		';
		
		$this->cms->renderHeader($this->lang('imgupload_image_editor'));
		$this->cms->renderMenu();
		$this->cms->addFrame($data['img_name'],$html);
		
	}
	
	public function saveImageInfo()
	{
		if(isset($_GET['iid']))
		{
			if(is_numeric($_GET['iid']))
			{
				$img_id = $_GET['iid'];
			}
			else
			{
				$this->cms->error('','index.php');
			}
		}
		else
		{
			$this->cms->error('','index.php');
		}
		
		require_once("core/tools/string.php");
		
		$_POST = array_sql_escape($_POST);
		$_POST = array_html_entity($_POST);
		
		$img_name = $_POST['img_name'];
		$description = $_POST['description'];
		
		$this->cms->sql_query("UPDATE %prefix%user_images SET img_name='$img_name',description='$description' WHERE id=$img_id");
		
		$this->imageEditForm();
	}
}





?>